package com.sofwin.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sofwin.Constants;
import com.sofwin.dto.NavsDto;
import com.sofwin.pojo.Navs;
import com.sofwin.pojo.SUser;
import com.sofwin.service.ResourceService;
import com.sofwin.service.UserService;

@Controller
@RequestMapping("/system")
public class SystemController {
	@Autowired
	private ResourceService resourceService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/resources")
	@ResponseBody
	public List<NavsDto> getResources(HttpSession session){
		SUser user = (SUser)session.getAttribute(Constants.CURRENT_USER);
		return resourceService.listResourcesByRoleId(user.getRoleId());
	}
	@RequestMapping("/resource/data")
	public String toResource(Model model) throws JsonProcessingException {
		List<NavsDto> navs = resourceService.listResources();
		List<Map> result = new ArrayList<Map>();
		for(NavsDto dto :navs) {
			Map map = new HashMap();
			map.put("name", dto.getTitle());
			map.put("open", true);
			List<Map> children = new ArrayList<Map>();
			for(Navs nav:dto.getChildren()) {
				Map map2 = new HashMap();
				map2.put("name", nav.getTitle());
				children.add(map2);
			}
			// children封装完成了
			map.put("children", children);
			result.add(map);
		}
		ObjectMapper mapper = new ObjectMapper();
		String str = mapper.writeValueAsString(result);
		System.out.println(str);
		model.addAttribute("data", str);
		return "resource";
	}
	
	@RequestMapping("toLogin")
	public String toLogin() {
		return "redirect:/login.jsp";
	}
	@PostMapping("checkLogin")
	public String checkLogin(SUser user,HttpSession session,String code) {
//		String mcode = session.getAttribute("code").toString();
//		if(!mcode.toUpperCase().equals(code.toUpperCase())) {
//			return toLogin();
//		}
		boolean status = userService.checkLogin(user);
		if(status) {
			// 登录成功
			user = userService.selectUserByUserNameAndPwd(user);
			session.setAttribute(Constants.CURRENT_USER, user);
			return "index";
		}
		return toLogin();
	}

}
